//
//  NetworkTools.swift
//  swift -AFN
//
//  Created by 王、小胜 on 16/7/26.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

import AFNetworking

/*
App Key：https://api.weibo.com/oauth2/authorize?client_id=3090702170&redirect_uri=http://www.baidu.com
App Secret：79e0c36d00aae627174c5bede0ff5579

redirect_uri	http://www.baidu.com


App Key：3090702170
App Secret：79e0c36d00aae627174c5bede0ff5579
*/


/// HTTP 请求方法枚举
enum HMRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}


// MARK: 网络工具
class NetworkTools: AFHTTPSessionManager {
    
    //MARK - 应用程序信息
    private let appKey = "3090702170"
    private let appSecret = "79e0c36d00aae627174c5bede0ff5579"
    private let redirectUrl = "http://www.baidu.com"
    
    
    ///网络请求完成回调，类似于OC的typedefine
    typealias RequestCallBack = (result: AnyObject?, error: NSError?)->()
    
    // 单例
    static let sharedTools: NetworkTools = {
        
        let tools = NetworkTools(baseURL: nil)
        
        // 设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    ///返回token字典
    private var tokenDict:[String: AnyObject]? {
        //判断touken是否有效
        if let token = UserAccountViewModel.sharedUserAccount.accessToken{
            return ["access_token":token]
        }
        return nil
    }
}
//MARK : - 加载用户信息
extension NetworkTools {
    
    func loadUserInfo(uid: String,  finished: RequestCallBack){
        
        //1.获取token字典
        guard var params = tokenDict else {
            //如果字典为空，通知调用方 token 无效
            finished(result: nil, error:NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message" : "token为空"]))
            
               return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
         params["uid"] = uid
        
        request(.GET, URLString: urlString, parameters: params, finished: finished)
    }
}
// MARK :- OAuth授权网络方法
extension NetworkTools {
    ///OAuth授权网络方法
    
    ///see:[https://api.weibo.com/oauth2/authorize](https://api.weibo.com/oauth2/authorize)
    var oauthURL:NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
    }
    
    
    ///加载 AccessToken
    func loadAccessToken(code:String, finished: RequestCallBack){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id":appKey,
        "client_secret":appSecret,
        "grant_type":"authorization_code",
        "code":code,
        "redirect_uri":redirectUrl]
        
        request(.POST, URLString: urlString, parameters: params, finished: finished)
        
///MARK - 测试用
//        ///测试接口文档
//        //1.设置相应格式是二进制
//        responseSerializer = AFHTTPResponseSerializer()
//        //2.发起网络请求
//        
//        POST(urlString, parameters: params, success: { (_, result) -> Void in
//            //将二进制数据转化成字符串
//            let json = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
//            
//            //"access_token":"2.00uVCWDGApQK4Def97e25407X3kmsC"
//            //"remind_in":"157679999"
//            //"expires_in":157679999
//            //"uid":"5548762162"
//            
//            print(json)
//            
//            
//            },failure: nil)
        
    }
}

// MARK: - 封装 AFN 网络方法
extension NetworkTools {
    
    /// 网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调
    func request(method: HMRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: RequestCallBack) {
        
        // 定义成功回调
        let success = { (task: NSURLSessionDataTask, result: AnyObject?) -> Void in
            finished(result: result, error: nil)
        }
        
        // 定义失败回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            // 在开发网络应用的时候，错误不要提示给用户，但是错误一定要输出！
            print(error)
            finished(result: nil, error: error)
        }
        
        if method == HMRequestMethod.GET {
            GET(URLString, parameters: parameters, success: success, failure: failure)
        } else {
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
        
//                if method == HMRequestMethod.GET {
//        
//                    GET(URLString, parameters: parameters, success: { (_, result) -> Void in
//        
//                        finished(result: result, error: nil)
//        
//                        }) { (_, error) -> Void in
//        
//                            // 在开发网络应用的时候，错误不要提示给用户，但是错误一定要输出！
//                            print(error)
//                            finished(result: nil, error: error)
//                    }
//                } else {
//        
//                    POST(URLString, parameters: parameters, success: { (_, result) -> Void in
//        
//                        finished(result: result, error: nil)
//        
//                        }) { (_, error) -> Void in
//        
//                            // 在开发网络应用的时候，错误不要提示给用户，但是错误一定要输出！
//                            print(error)
//                            finished(result: nil, error: error)
//                    }
//                }

        
    }
    
    
    
    
}
